﻿#-*- coding:UTF-8 -*-
import os
import os.path
import shutil
import sys

rootdir=u"F:\\枪战片"  #搜索的路径
targetDir=u'F:\\枪战片\\枪战'	#目标路径
canMoveList =["mp4","mkv","wmv","rmvb","avi","rm","3gp","MPG","flv","zip"]


def getParam(arguments):

    argLen = len(arguments)
    # print  argLen
    targetPath = ""
    sourcePath = ""
    for i in range(0,argLen):
        param = arguments[i]
        if param.startswith('-'):
            option = param[1:]
            if option == "tp":
                if i+1 < argLen:
                    targetPath = arguments[i+1]
                else:
                    print "param error!"

            if option == "sp":
                if i+1 < argLen:
                    sourcePath = sys.argv[i+1]
                else:
                    print "param error!"

    if  os.path.exists(sourcePath):

        # if param is nil.set a default dir named
        if len(targetPath)==0 :
            targetPath = sourcePath+"\\tmp"

        # if is not exist.make a dir
        if not os.path.exists(targetPath):
            os.mkdir(targetPath)

    else:
        print  "source path is not exist"

    return (sourcePath,targetPath)


# 文件夹根据名字排序
def sort(dicts):
	newDict={}
	newArray =[]
	for item in dicts.items():
		newArray.append(item)
		
	print '文件类型有'+str(len(newArray))+'种'
	newArray.sort(lambda x,y:cmp(y[1],x[1]))
				
	for item in newArray:
		print "file type:" + item[0] +" count:"+str(item[1])

	return newArray
# 创建以文件后缀为名字的文件夹		
def mkdir_by_sufix(sufix):
	tmp_targetFile = os.path.join(targetDir,str(sufix) )
	if not os.path.exists(tmp_targetFile):
		print "new dir"+tmp_targetFile
		os.makedirs(tmp_targetFile)     
# 创建文件夹
def my_mkdir(dir_array):
	for item in dir_array:
		print "tpye"+str(item[0])
		tmp_targetFile = os.path.join(targetDir,str(item[0])) 
		if not os.path.exists(tmp_targetFile):
			print "new dir"+tmp_targetFile
			os.makedirs(tmp_targetFile)     

def deleteAndMove(originFile,destinationFile):
	try:
		shutil.move(originFile,destinationFile)
		# print "from :"+originFile+" to:"+destinationFile
		# os.remove(destinationFile)
	except Exception:
		print 'io exception!!!',originFile,'-->',destinationFile
	
def isCanMove(sufix):
	for sub in canMoveList:
		if sub==sufix:
			return True
		elif sufix=='ini':
			return False
		else:
			return True

#***********程序主流程*************


paramRootdir,paramtargetDir = getParam(sys.argv)

if len(paramRootdir)>0 and len(paramtargetDir)>0:
    rootdir = paramRootdir
    targetDir = paramtargetDir

dict={}
filecount=0
for parent,dirnames,filenames in os.walk(rootdir):
	for filename in filenames:
		sufix = os.path.splitext(filename)[1][1:]
		iCanMove = isCanMove(sufix)	
		if iCanMove==True:
			originPath=os.path.join(parent,filename)
				
			if os.path.isfile(originPath)==True:
				destinationPath=os.path.join(targetDir,sufix+'/'+filename)
				mkdir_by_sufix(str(sufix))
				# print "moving:"+originPath+" --->"+destinationPath
				deleteAndMove(originPath,destinationPath)
				filecount+=1
		if dict.has_key(sufix):
			dict[sufix] += 1
		else:
			dict[sufix]=1
	# os.remove(parent)

print 'from ',rootdir,' to ',targetDir
for item in dict.items():
	print "%s : %s" % item	
print 'moved file count:',str(filecount),
# newArray=sort(dict)
# my_mkdir(newArray)